package middlewares

import (
	"awesome-devops/applications/backend/modules/define"
	"awesome-devops/applications/backend/modules/services"
	"gitee.com/jjawesomejj/awesome-util/helper/timeHelper"
	"gitee.com/jjawesomejj/awesomehttp/system/httpContext"
	"gitee.com/jjawesomejj/awesomehttp/system/middlewares"
)

type AuthMiddleware struct {
	middlewares.BaseMiddleware
}

func (baseMiddleware *AuthMiddleware) Handle(ctx *httpContext.HttpContext, next func(ctx2 *httpContext.HttpContext) interface{}) (res interface{}) {
	if ctx.Request.Header.Get("authorization") == "" {
		ctx.ResponseContent = define.BaseResponse{
			Msg:   "请登录",
			Errno: 10003,
			Ptime: timeHelper.NowFloat() - ctx.StartAt,
			Data:  make(map[string]interface{}),
		}
		return nil
	}
	service := services.UserService{}
	user, err := service.GetUserByAccessToken(ctx.Request.Header.Get("authorization"))
	if err != nil {
		ctx.ResponseContent = define.BaseResponse{
			Msg:   "请登录",
			Errno: 10003,
			Ptime: timeHelper.NowFloat() - ctx.StartAt,
			Data:  make(map[string]interface{}),
		}
		return nil
	}
	ctx.SetValue("login_user", user)
	return next(ctx)
}
